import React from 'react';
import { browserHistory } from 'react-router';
import { Form, Input, Select, InputNumber, Checkbox, DatePicker, Row, Col, Button, Modal, Icon, Spin, Card } from 'antd';
const TextArea = Input.TextArea;
const Option = Select.Option;
const FormItem = Form.Item;

import TableView from './../TableView';
import * as actions from './../../../actions/backstage/productAction';

class purviewList extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
          uId: '',
          delId: '',
          delSensitiveWord: '',
          findSensitiveWords: GLOBAL.baseURL + "webAPI/product/findProducts",
          visibleDeleteAlert: false,
          visibleAddAlert: false,
          addProductPage: false,
          updateLoading: false,
          selectData: {},
          serviceData: [],
          searchObject: {},
          alertTitle: '添加',
          createTimer: null,
          updateTimer: null,
          sensitiveWord: null
        }
    }
    // 提交商品表单
    addAndEditSubmit(e) {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
          if (!err) {
              if(this.state.alertTitle == '添加'){
                  values.qualityGuaranteePeriod = values.qualityGuaranteePeriod.toString();
                  values.status = "inactive";
                  this.setState({
                    visibleAddAlert: true,
                    selectData: values
                  });
              }else if(this.state.alertTitle == '修改'){
                  this.state.selectData.pName = values.pName;
                  this.state.selectData.description = values.description;
                  delete this.state.selectData.colorIndex;
                  this.setState({
                    visibleAddAlert: true
                  });
              }
          }
        });
    }
    onConfirmAdd(){
        this.setState({visibleAddAlert: false, updateLoading: true});
        actions.addOrEditProduct(this, this.state.selectData);
    }
    deleteSensitiveWords(id, sensitiveWord){
        return;
        this.setState({visibleDeleteAlert: true, delId: id, delSensitiveWord: sensitiveWord});
    }
    cloneObj(obj){
        var str, newobj = obj.constructor === Array ? [] : {};
        if(typeof obj !== 'object'){
            return;
        } else if(window.JSON){
            str = JSON.stringify(obj), //序列化对象
            newobj = JSON.parse(str); //还原
        } else {
            for(var i in obj){
                newobj[i] = typeof obj[i] === 'object' ? cloneObj(obj[i]) : obj[i];
            }
        }
        return newobj;
    }
    modifySensitiveWords(item){
        this.setState({
          alertTitle: '修改',
          addProductPage: true,
          selectData: this.cloneObj(item),
          createTimer: ((item.createTime == undefined)?null:new Date(item.createTime).Format("yyyy-MM-dd hh:mm:ss")),
          updateTimer: ((item.updateTime == undefined)?null:new Date(item.updateTime).Format("yyyy-MM-dd hh:mm:ss")),
          sensitiveWord: null
        });
    }
    onConfirmDelete(){
        actions.removeSensitiveWord(this, this.state.delId);
    }
    getServiceData(data) {
        for (var i = 0; i < data.length; i++) {
          try{
            if(this.state.serviceData[i].colorIndex != undefined){
              data[i].colorIndex = this.state.serviceData[i].colorIndex
            }
          }catch(e){
              data[i].colorIndex = parseInt(Math.random()*17);
          }
        }
        this.setState({serviceData: data});
    }
    onImgLoad(e){
        $(e.currentTarget).css("backgroundImage", "none");
    }
    routerProductDetail(id){
        browserHistory.push("/backstage/productManage/productDetail/" + id);
    }
    onChangeProductStatus(item, flag, e){
        e.stopPropagation();
        if(flag == "lock"){
            if(confirm("你确定：启用 此商品？")){
              item.status = "active";
              actions.changeStatus(this, item, "manage");
            }
        }else if(flag == "unLock"){
            if(confirm("你确定：禁用 此商品？")){
              item.status = "inactive";
              actions.changeStatus(this, item, "manage");
            }
        }
    }
    renderItem(item, index) {
      var imgCoverPicture = null;
      if(item.productPic != undefined){
          imgCoverPicture = <div className="divUserHead">
            <img className="imgCoverPicture" src={"http://tinsley.oss-cn-shenzhen.aliyuncs.com/" + item.productPic} onLoad={this.onImgLoad.bind(this)}/>
            <img className="imgPromotion" style={{display: ((item.setTopType == true)?'block':'none')}} src="/src/styles/images/Promotion.png"/>
          </div>
      }else{
          imgCoverPicture = <div className="divUserHead">
            <img className="imgCoverPicture" src="/src/styles/images/listDefault.png"/>
            <img className="imgPromotion" style={{display: ((item.setTopType == true)?'block':'none')}} src="/src/styles/images/Promotion.png"/>
          </div>
      }
      return (
          <Card key={index} onClick={this.routerProductDetail.bind(this, item.id)} className="divItemLine">
              {imgCoverPicture}
              <div className="userInfo" style={{marginTop: '0px'}}>
                  <div className="divArticleTitle1" title={'Name: ' + ((item.productName == undefined)?"":item.productName) + ', Brand Name: ' + ((item.brandName == undefined)?"":item.brandName)}>
                      <span>{'名字: ' + ((item.productName == undefined)?"":item.productName)}{'，品牌: ' + ((item.brandName == undefined)?"":item.brandName)}</span>
                  </div>
                  <div className="divArticleTitle1">
                      <span>{'原价格(Rm): ' + ((item.price == undefined)?"":item.price)}{'，折扣价(Rm): ' + ((item.discountPrice == undefined)?"":item.discountPrice)}</span>
                  </div>
                  <div className="divArticleContent2" title={((item.placeOfProduction == undefined)?"":item.placeOfProduction)}>
                      <span>{'产地: ' + ((item.placeOfProduction == undefined)?"":item.placeOfProduction)}</span>
                  </div>
                  <div className="divArticleContent2" title={((item.reminder == undefined)?"":item.reminder)}>
                      <span>{'温馨提示: ' + ((item.reminder == undefined)?"":item.reminder)}</span>
                  </div>
                  <div className="divContent">
                      <span>{'创建: ' + ((item.commitTime == undefined)?"":new Date(item.commitTime).Format("yyyy-MM-dd"))}</span>
                      <span>{((item.updateTime == undefined)?"":", 修改: " + new Date(item.updateTime).Format("yyyy-MM-dd"))}</span>
                  </div>
                  <div className="pOverview">
                      <span style={{color: '#9a9a9a'}}>
                        <span title="浏览量"><Icon type="eye" className="iconEye"/>{item.browseNumbers}</span>
                        <span title="库存"><Icon type="shop" className="iconLike"/>{item.stock}</span>
                      </span>
                      <Icon onClick={this.onChangeProductStatus.bind(this, item, "lock")} type="lock" className="iconLock" style={{display: ((item.status == 'inactive')?"inline-block":'none')}} title="当前状态：未公开"/>
                      <Icon onClick={this.onChangeProductStatus.bind(this, item, "unLock")} type="unlock" className="iconUnLock" style={{display: ((item.status == 'inactive')?"none":'inline-block')}} title="当前状态：公开"/>
                  </div>
              </div>
          </Card>
      );
    }
    resetFields(){
      this.setState({addProductPage: false});
      this.props.form.resetFields();
    }
    bindAddSensitiveWords(){
      this.setState({
        selectData: {},
        addProductPage: true,
        alertTitle: '添加',
        createTimer: null,
        updateTimer: null,
        sensitiveWord: null
      });
    }
    //屏蔽回车
    screenedCarriageReturn(e){
      if (e.keyCode === 13) {
          e.preventDefault();
          return false;
      }
    }
    changeType(value){
      if(value == "-1"){
        delete this.state.searchObject.type;
      }else {
        this.state.searchObject.type = value;
      }
    }
    changeStatus(value){
      if(value == "-1"){
        delete this.state.searchObject.status;
      }else {
        this.state.searchObject.status = value;
      }
    }
    btnSearch(){
      this.setState({searchObject: this.state.searchObject});
      this.refs["tableView"].refreshData();
    }
    render() {
        if(this.props.params.id == undefined){
        var serverList = null;
        const { getFieldDecorator } = this.props.form
        const formItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 16 }
        }

        if(this.state.serviceData.length != 0){
            serverList = <div>
              {
                  this.state.serviceData.map((item, index) => {
                      return this.renderItem(item, index);
                  })
              }
            </div>
        }else{
            serverList = <div className="divEmptyData">对不起，没有相关商品数据。</div>
        }
        return (
          <div className="divTagS">
            <div style={{textAlign: 'right', marginBottom: '10px'}}>
                <div className="divProductSearch">
                  商品类型: <Select defaultValue="-1" style={{ width: 120, marginRight: '10px' }} onChange={this.changeType.bind(this)}>
                    <Option value="-1">所有产品</Option>
                    <Option value="1">推荐品牌</Option>
                    <Option value="2">女孩护肤</Option>
                    <Option value="3">面膜</Option>
                    <Option value="4">彩妆/口红</Option>
                    <Option value="5">个人护理</Option>
                    <Option value="6">保健产品</Option>
                  </Select>
                  状态: <Select defaultValue="-1" style={{ width: 120, marginRight: '10px' }} onChange={this.changeStatus.bind(this)}>
                    <Option value="-1">所有状态</Option>
                    <Option value="active">启用</Option>
                    <Option value="inactive">禁用</Option>
                  </Select>
                  <Button type="primary" icon="search" onClick={this.btnSearch.bind(this)}>搜索</Button>
                </div>

                <Button type="primary" icon="plus" onClick={this.bindAddSensitiveWords.bind(this)}>添加产品</Button>
            </div>
            <div className="divTagContent">
                {serverList}
                <TableView ref="tableView"
                   getServiceData={this.getServiceData.bind(this)}
                   isService={true} searchObject={this.state.searchObject} pageNum={10}
                   url={this.state.findSensitiveWords} method="post"/>
            </div>
            <Modal
              visible={this.state.addProductPage}
              title={this.state.alertTitle + " 商品"}
              width="650px"
              maskClosable={false}
              footer={null}
              wrapClassName="vertical-center-modal"
              onCancel={this.resetFields.bind(this)}
            >
              <Spin spinning={this.state.updateLoading} tip="Update Product...">
                <Form onSubmit={this.addAndEditSubmit.bind(this)} style={{width: '100%'}}>
                    <div className="divFromScroll">
                      <FormItem
                          label="商品名"
                          {...formItemLayout}>
                          {getFieldDecorator('productName', {
                            rules: [{ required: true, message: '商品名 必填。'}],
                            initialValue: this.state.selectData.pName
                          })(
                            <Input placeholder="请输入商品名..." onPressEnter={this.screenedCarriageReturn.bind(this)}/>
                          )}
                      </FormItem>

                      <Row gutter={8}>
                        <Col span={12}>
                          <FormItem
                              label="原价格"
                              labelCol={{span: 10, offset: 2}}
                              wrapperCol={{span: 12, offset: 0}}>
                              {getFieldDecorator('price', {
                                rules: [{ required: true, message: '原价格 必填。'}],
                                initialValue: (this.state.selectData.price)?this.state.selectData.price:0
                              })(
                                <InputNumber
                                  min={0}
                                  precision={2}
                                  style={{width: '120px', marginLeft: '2px'}}
                                  formatter={value => `$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                                  parser={value => value.replace(/\$\s?|(,*)/g, '')}
                                />
                              )}
                          </FormItem>
                        </Col>
                        <Col span={10}>
                          <FormItem
                              label="折扣价"
                              labelCol={{span: 10, offset: 0}}
                              wrapperCol={{span: 12, offset: 0}}>
                              {getFieldDecorator('discountPrice', {
                                rules: [{ required: true, message: '折扣价 必填。'}],
                                initialValue: (this.state.selectData.discountPrice)?this.state.selectData.discountPrice:0
                              })(
                                <InputNumber
                                  min={0}
                                  precision={2}
                                  style={{width: '120px'}}
                                  formatter={value => `$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                                  parser={value => value.replace(/\$\s?|(,*)/g, '')}
                                />
                              )}
                          </FormItem>
                        </Col>
                      </Row>
                      <Row gutter={8}>
                        <Col span={12}>
                          <FormItem
                              label="库存"
                              labelCol={{span: 10, offset: 2}}
                              wrapperCol={{span: 12, offset: 0}}>
                              {getFieldDecorator('stock', {
                                rules: [{ required: true, message: '库存 必填。'}],
                                initialValue: (this.state.selectData.stock)?this.state.selectData.stock:0
                              })(
                                <InputNumber min={0} style={{width: '120px', marginLeft: '2px'}}/>
                              )}
                          </FormItem>
                        </Col>
                        <Col span={10}>
                          <FormItem
                              label="保质期"
                              labelCol={{span: 10, offset: 0}}
                              wrapperCol={{span: 12, offset: 0}}>
                              {getFieldDecorator('qualityGuaranteePeriod', {
                                rules: [{ required: true, message: '保质期 必填。'}],
                                initialValue: (this.state.selectData.qualityGuaranteePeriod)?parseInt(this.state.selectData.qualityGuaranteePeriod):0
                              })(
                                <InputNumber />
                              )}
                              <span className="ant-form-text"> 天</span>
                          </FormItem>
                        </Col>
                      </Row>
                      <Row gutter={8}>
                        <Col span={12}>
                          <FormItem
                              label="类型"
                              labelCol={{span: 10, offset: 2}}
                              wrapperCol={{span: 12, offset: 0}}>
                              {getFieldDecorator('type', {
                                rules: [{ required: true, message: '类型 必填。'}],
                                initialValue: (this.state.selectData.type)?this.state.selectData.type:"1"
                              })(
                                <Select
                                  placeholder="选择类型"
                                  onChange={this.handleSelectChange}
                                  style={{width: '120px'}}
                                >
                                  <Option value="1">推荐品牌</Option>
                                  <Option value="2">女孩护肤</Option>
                                  <Option value="3">面膜</Option>
                                  <Option value="4">彩妆/口红</Option>
                                  <Option value="5">个人护理</Option>
                                  <Option value="6">保健产品</Option>
                                </Select>
                              )}
                          </FormItem>
                        </Col>
                        <Col span={10}>
                          <FormItem
                              labelCol={{span: 10, offset: 0}}
                              wrapperCol={{span: 12, offset: 0}}>
                              {getFieldDecorator('mustCheckOut', {
                                rules: [{ required: false}],
                                initialValue: (this.state.selectData.mustCheckOut)?this.state.selectData.mustCheckOut:false,
                                valuePropName: 'checked'
                              })(
                                <Checkbox style={{marginLeft: '36px'}}>每日必看</Checkbox>
                              )}
                          </FormItem>
                        </Col>
                      </Row>
                      <FormItem
                          label="置顶类型"
                          {...formItemLayout}>
                          {getFieldDecorator('setTopType', {
                            rules: [{ required: true, message: '置顶类型 必填。'}],
                            initialValue: (this.state.selectData.setTopType)?this.state.selectData.setTopType:"NO"
                          })(
                            <Select
                              placeholder="选择置顶类型"
                              onChange={this.handleSelectChange}
                            >
                              <Option value="YES">置顶</Option>
                              <Option value="NO">取消置顶</Option>
                            </Select>
                          )}
                      </FormItem>
                      <FormItem
                          label="标题"
                          {...formItemLayout}>
                          {getFieldDecorator('title', {
                            rules: [{ required: true, message: '标题 必填。'}],
                            initialValue: this.state.selectData.title
                          })(
                            <Input style={{ minWidth: 260 }} placeholder="请输入标题..." onPressEnter={this.screenedCarriageReturn.bind(this)}/>
                          )}
                      </FormItem>

                      <FormItem
                          label="尺寸"
                          {...formItemLayout}>
                          {getFieldDecorator('sizes', {
                            rules: [{ required: true, message: '尺寸 必填。'}],
                            initialValue: this.state.selectData.sizes
                          })(
                            <Select
                              mode="tags"
                              size="default"
                              placeholder="请输入尺寸，回车..."
                              style={{ width: '100%' }}
                              tokenSeparators={[',','|']}
                              onInputKeyDown={this.screenedCarriageReturn.bind(this)}
                              getPopupContainer={triggerNode => triggerNode.parentNode}
                            ></Select>
                          )}
                      </FormItem>
                      <FormItem
                          label="产品颜色"
                          {...formItemLayout}>
                          {getFieldDecorator('productColors', {
                            rules: [{ required: true, message: '产品颜色 必填。'}],
                            initialValue: this.state.selectData.productColors
                          })(
                            <Select
                              mode="tags"
                              size="default"
                              placeholder="请输入产品颜色，回车..."
                              style={{ width: '100%' }}
                              tokenSeparators={[',','|']}
                              onInputKeyDown={this.screenedCarriageReturn.bind(this)}
                              getPopupContainer={triggerNode => triggerNode.parentNode}
                            ></Select>
                          )}
                      </FormItem>

                      <FormItem
                          label="商品品牌"
                          {...formItemLayout}>
                          {getFieldDecorator('brandName', {
                            rules: [{ required: false}],
                            initialValue: this.state.selectData.brandName
                          })(
                            <Input style={{ minWidth: 260 }} placeholder="请输入品牌（如：香莱尔）..." onPressEnter={this.screenedCarriageReturn.bind(this)}/>
                          )}
                      </FormItem>
                      <FormItem
                          label="产地"
                          {...formItemLayout}>
                          {getFieldDecorator('placeOfProduction', {
                            rules: [{ required: false}],
                            initialValue: this.state.selectData.placeOfProduction
                          })(
                            <Input style={{ minWidth: 260 }} placeholder="请输入产地..." onPressEnter={this.screenedCarriageReturn.bind(this)}/>
                          )}
                      </FormItem>
                      <FormItem
                          label="商品成分"
                          {...formItemLayout}>
                          {getFieldDecorator('ingredients', {
                            rules: [{ required: false}],
                            initialValue: this.state.selectData.ingredients
                          })(
                            <TextArea style={{ minWidth: 260, resize: 'none' }} type="textarea" rows={2} placeholder="请输入成分描述..." />
                          )}
                      </FormItem>
                      <FormItem
                          label="温馨提示"
                          {...formItemLayout}>
                          {getFieldDecorator('reminder', {
                            rules: [{ required: false}],
                            initialValue: this.state.selectData.reminder
                          })(
                            <TextArea style={{ minWidth: 260, resize: 'none' }} rows={2} placeholder="请输入温馨提示..." />
                          )}
                      </FormItem>
                    </div>
                    <FormItem wrapperCol={{ span: 25, offset: 0 }} style={{ marginTop: 24,textAlign: 'center' }}>
                        <Button type="primary" className="btnPersonalClose" htmlType="submit" icon="save">{this.state.alertTitle + " 商品"}</Button>
                        <Button icon="close" onClick={this.resetFields.bind(this)}>取 消</Button>
                    </FormItem>
                </Form>
              </Spin>
            </Modal>

            <Modal title="提示：" maskClosable={false} wrapClassName="vertical-center-modal" visible={this.state.visibleDeleteAlert} onOk={this.onConfirmDelete.bind(this)} onCancel={()=>{this.setState({visibleDeleteAlert: false})}}>
                您确定要删除：{this.state.delSensitiveWord} 吗？
            </Modal>
            <Modal title="提示：" maskClosable={false} wrapClassName="vertical-center-modal" visible={this.state.visibleAddAlert} onOk={this.onConfirmAdd.bind(this)} onCancel={()=>{this.setState({visibleAddAlert: false})}}>
                你确定要 {this.state.alertTitle} 产品?
            </Modal>
          </div>
        )
      }else {
        return(this.props.children)
      }
    }
}

purviewList = Form.create()(purviewList)
export default purviewList;
